<?php
class UserBusi {
	
	/**
	 * 取得用户信息
	 */
	public function getUserById($condition) {
		global $mysqlTools;
		$condition = $mysqlTools->check_input ( $condition );
		$sql = "
        	SELECT
				su.userId,
				su.userLoginId,
				su.userPwd,
				su.userShortIndex,
				su.userIndex,
				su.userPhone,
				su.userTel,
				su.userEmail,
				su.userRecom1UserId,
				su.userRecom1LoginId,
				su.userQQ,
				su.userState,
				su.userCreateTime,
				su.userSex,
				sr.roleId,
				sr.roleDesc,
				su.userGold
			FROM
				sys_user su left join sys_user_role sur on su.userId=sur.userId 
				left join sys_role sr on sur.roleId=sr.roleId
			where
				1=1
        ";
		if (isset ( $condition ["userLoginId"] ) && ! empty ( $condition ["userLoginId"] )) {
			$sql = $sql . " and su.userLoginId=$condition[userLoginId]";
		}
		if (isset ( $condition ["userId"] ) && ! empty ( $condition ["userId"] )) {
			$sql = $sql . " and su.userId=$condition[userId]";
		}
		if (isset ( $condition ["userIsCenterUser"] ) && ! empty ( $condition ["userIsCenterUser"] )) {
			$sql = $sql . " and su.userIsCenterUser=$condition[userIsCenterUser]";
		}
		// 查询用户信息
		$list = $mysqlTools->selectSql ( $sql );
		if (is_array ( $list ) && ! empty ( $list ))
			return $list [0];
		else
			return array ();
	}
	
	public function findTenLevelUserByUserId($userId) {
		$list =  array();
		$condition = array(
				"userId"=>$userId
		);
		$userInfo = $this->getUserById($condition);
		if(empty($userInfo["userRecom1UserId"])){
			return $list;
		}
		$condition["userId"] = $userInfo["userRecom1UserId"];
		for($i = 0; $i < 10; $i ++) {
			$userInfo = $this->getUserById($condition);
			$list[] = $userInfo;
			if(empty($userInfo["userRecom1UserId"])){
				return $list;
			}
			$condition["userId"] = $userInfo["userRecom1UserId"];
		}
		return $list;
	}
	
	public function findTenLevelUserByLoginId($userLoginId) {
		$list =  array();
		$condition = array(
				"userLoginId"=>$userLoginId
		);
		$userInfo = $this->getUserById($condition);
		if(empty($userInfo["userRecom1UserId"])){
			return $list;
		}
		$condition["userId"] = $userInfo["userRecom1UserId"];
		if(array_key_exists("userLoginId",$condition)){
			unset($condition["userLoginId"]);
		}
		for($i = 0; $i < 10; $i ++) {
			$userInfo = $this->getUserById($condition);
			$list[] = $userInfo;
			if(empty($userInfo["userRecom1UserId"])){
				return $list;
			}
			$condition["userId"] = $userInfo["userRecom1UserId"];
		}
		return $list;
	}
	
	private function getMaxIndex($condition) {
		global $mysqlTools;
		$condition = $mysqlTools->check_input ( $condition );
		$sql = "select max(cast(conv(userShortIndex,32,10)as SIGNED)) shorIndex from sys_user where 1=1 
		";
		if (isset ( $condition ["userId"] )) {
			$sql = $sql . "and userRecom1UserId = $condition[userId]";
		} else {
			$sql = $sql . "and userRecom1UserId is null";
		}
		$users = $mysqlTools->selectSql ( $sql );
		if (is_array ( $users ) && ! empty ( $users )) {
			return $users [0] ["shorIndex"];
		}
		return null;
	}
	
	/**
	 * 添加注册用户角色
	 *
	 * @param array $key
	 *        	key list:
	 *        	userId, 用户主键Id
	 *        	roleName 角色Id
	 * @return boolean
	 */
	public function addUserRole($key) {
		global $mysqlTools;
		if (! isset ( $key ["userId"] ) || empty ( $key ["userId"] )) {
			return false;
		}
		if (! isset ( $key ["roleName"] ) || empty ( $key ["roleName"] )) {
			$key ["roleName"] = "member";
		}
		$userInfo = $this->getUserById ( $key );
		if (empty ( $userInfo )) {
			return false;
		}
		$key = $mysqlTools->check_input ( $key );
		$queryRoleSql = "select roleId from sys_role where roleName=$key[roleName]";
		$roleInfo = $mysqlTools->selectSql ( $queryRoleSql );
		if (empty ( $roleInfo )) {
			return false;
		}
		$roleInfo = $roleInfo [0];
		$sql = "INSERT INTO `sys_user_role` (`userId`, `roleId`) VALUES ($key[userId], $roleInfo[roleId])";
		return $mysqlTools->executeSql ( $sql );
	}
	
	/**
	 * 增加一个普通用户
	 *
	 * @param
	 *        	添加条件
	 * @return string
	 */
	public function addUser($condition) {
		global $mysqlTools;
		// 生成唯一ID
		$uniqid = getCurrentId ();
		$orgPwd = $condition ["userPwd"];
		$orgLoginId = $condition ["userLoginId"];
		$condition ['userPwd'] = md5 ( $condition ['userPwd'] );
		
		if (isset ( $condition ["userCenterLoginId"] ) && ! empty ( $condition ["userCenterLoginId"] )) {
			// 查询报单用户人信息
			$center = $condition;
			$center ["userLoginId"] = $condition ["userCenterLoginId"];
			$center ["userIsCenterUser"] = 1;
			$centerUserInfo = $this->getUserById ( $center );
			if (empty ( $centerUserInfo )) {
				return "报单用户没有找到";
			}
			$condition ["userCenterUserId"] = $centerUserInfo ["userId"];
		}
		if (isset ( $condition ["userRecom1LoginId"] ) && ! empty ( $condition ["userRecom1LoginId"] )) {
			// 查用推荐用户人信息
			$recommend = $condition;
			$recommend ["userLoginId"] = $condition ["userRecom1LoginId"];
			$recommendUserInfo = $this->getUserById ( $recommend );
			if(empty($recommendUserInfo)){
				return "推荐人没有找到";
			}
			if (empty ( $recommendUserInfo ["userIndex"] ) || empty ( $recommendUserInfo ["userShortIndex"] )) {
				return "推荐人序列号没有找到,请联系管理员";
			}
			if ( $recommendUserInfo ["userState"] == 4 ) {
				return "推荐人还没有被激活";
			}
			// 设置索引字段
			$currentIndex = $this->getMaxIndex ( array (
					"userId" => $recommendUserInfo ["userId"] 
			) );
			$shortIndex = 1;
			if (! is_null ( $currentIndex ) && ! empty ( $currentIndex )) {
				$shortIndex = $currentIndex + 1;
				$shortIndex = base_convert ( $shortIndex, 10, 32 );
			}
			$index = $recommendUserInfo ["userIndex"];
			$condition ["userShortIndex"] = $shortIndex;
			$condition ["userIndex"] = $index . "_" . $shortIndex;
			// 设置一级推荐用户
			$condition ["userRecom1UserId"] = $recommendUserInfo ["userId"];
			
			if (! empty ( $recommendUserInfo ["userRecom1UserId"] ) && ! empty ( $recommendUserInfo ["userRecom1LoginId"] )) {
				// 设置二级推荐用户
				$condition ["userRecom2UserId"] = $recommendUserInfo ["userRecom1UserId"];
				$condition ["userRecom2LoginId"] = $recommendUserInfo ["userRecom1LoginId"];
			}
			if (! empty ( $recommendUserInfo ["userRecom1UserId"] ) && ! empty ( $recommendUserInfo ["userRecom1LoginId"] )) {
				$recommendThree = array (
						"userLoginId" => $recommendUserInfo ["userRecom1LoginId"] 
				);
				// 设置三级用户
				$recommendThreeUserInfo = $this->getUserById ( $recommendThree );
				if (! empty ( $recommendThreeUserInfo )) {
					$condition ["userRecom3UserId"] = $recommendThreeUserInfo ["userRecom1UserId"];
					$condition ["userRecom3LoginId"] = $recommendThreeUserInfo ["userRecom1LoginId"];
				}
			}
		} else {
			// 设置索引字段
			$currentIndex = $this->getMaxIndex ( array () );
			$shortIndex = 1;
			if (! is_null ( $currentIndex ) && ! empty ( $currentIndex )) {
				$shortIndex = $currentIndex + 1;
				$shortIndex = base_convert ( $shortIndex, 10, 32 );
			}
			$condition ["userShortIndex"] = $shortIndex;
			$condition ["userIndex"] = $shortIndex;
		}
		if (! isset ( $condition ["userCenterUserId"] )) {
			$condition ["userCenterUserId"] = null;
		}
		if (! isset ( $condition ["userQQ"] )) {
			$condition ["userQQ"] = null;
		}
		if (! isset ( $condition ["userEmail"] )) {
			$condition ["userEmail"] = null;
		}
		if (! isset ( $condition ["userAvatarId"] )) {
			$condition ["userAvatarId"] = null;
		}
		if (! isset ( $condition ["userRecom1UserId"] )) {
			$condition ["userRecom1UserId"] = null;
		}
		if (! isset ( $condition ["userRecom2UserId"] )) {
			$condition ["userRecom2UserId"] = null;
		}
		if (! isset ( $condition ["userRecom3UserId"] )) {
			$condition ["userRecom3UserId"] = null;
		}
		if (! isset ( $condition ["userRecom1LoginId"] )) {
			$condition ["userRecom1LoginId"] = null;
		}
		if (! isset ( $condition ["userRecom2LoginId"] )) {
			$condition ["userRecom2LoginId"] = null;
		}
		if (! isset ( $condition ["userRecom3LoginId"] )) {
			$condition ["userRecom3LoginId"] = null;
		}
		if (! isset ( $condition ["userIndex"] )) {
			$condition ["userIndex"] = null;
		}
		if (! isset ( $condition ["userShortIndex"] )) {
			$condition ["userShortIndex"] = null;
		}
		
		// 参数处理注入SQL安全问题
		$condition = $mysqlTools->check_input ( $condition );
		// 处理null值,如果值为null数据库也置为null
		$condition = $mysqlTools->check_null ( $condition );
		$mysqlTools->startTransaction ();
		$sql = "
    		insert into sys_user (userId,userLoginId,userPwd,userIndex,userShortIndex,
				      userPhone,userTel,userQQ,userEmail,userAvatarId,
				      userState,userSex,userRealName,userRecom1UserId,userRecom1LoginId,
				      userRecom2UserId,userRecom2LoginId,userRecom3UserId,userRecom3LoginId,
				      userCenterUserId,userCenterLoginId,userCreateTime)
    		values($uniqid,$condition[userLoginId],$condition[userPwd],$condition[userIndex],$condition[userShortIndex],
					  $condition[userPhone],$condition[userTel],
				      $condition[userQQ],$condition[userEmail],
				      $condition[userAvatarId],4,$condition[userSex],$condition[userRealName],
				      $condition[userRecom1UserId],$condition[userRecom1LoginId],
					  $condition[userRecom2UserId],$condition[userRecom2LoginId],
					  $condition[userRecom3UserId],$condition[userRecom3LoginId],
				      $condition[userCenterUserId],$condition[userCenterLoginId],now())";
		$result = $mysqlTools->executeSql ( $sql );
		if (! $result) {
			$mysqlTools->rollback ();
			return "注册失败,请稍后在试";
		}
		$addRoleResult = $this->addUserRole ( array (
				"userId" => $uniqid 
		) );
		if (! $addRoleResult) {
			$mysqlTools->rollback ();
			return "添加用户角色失败,请联系管理员";
		}
		$mysqlTools->commitTransaction ();
		// 自动登陆代码
		// tsLoad ( '/manage/busi/SysUserBusi.class.php' );
		// $sysUserBusi = new SysUserBusi ();
		// $loginCondition = array (
		// "userLoginId" => $orgLoginId,
		// "userPwd" => $orgPwd
		// );
		// $sysUserBusi->loginSysUser ( $loginCondition );
		return "success";
	}
	/**
	 * 取得用户子用户列表
	 */
	private function getUserListByPid($userId) {
		global $mysqlTools;
		$userId = $mysqlTools->check_input ( $userId );
		$sql = "
        	select
				u.userId,
				u.userIndex,
				s.roleLevel
			from
				sys_user u inner join sys_user_role r on u.userId = r.userId
				inner join sys_role s on s.roleId = r.roleId
			where
				u.userRecom1UserId = $userId and u.userState != 4";
		// 查询用户信息
		$list = $mysqlTools->selectSql ( $sql );
		if (is_array ( $list )) {
			return $list;
		} else {
			return array ();
		}
	}
	
	/**
	 * 取得用户信息
	 */
	private function getUserRoleInfoById($userId) {
		global $mysqlTools;
		$userId = $mysqlTools->check_input ( $userId );
		$sql = "
        	select
				u.userId,
				u.userIndex,
				u.userRecom1UserId,
				s.roleLevel
			from
				sys_user u inner join sys_user_role r on u.userId = r.userId
				inner join sys_role s on s.roleId = r.roleId
			where
				u.userId = $userId and u.userState != 4";
		// 查询用户信息
		$list = $mysqlTools->selectSql ( $sql );
		if (is_array ( $list ) && ! empty ( $list )) {
			return $list [0];
		} else {
			return array ();
		}
	}
	private function queryRole() {
		global $mysqlTools;
		$sql = "
			select roleLevel level,roleUpgradeCount count from sys_role s where s.roletype = 2 order by roleLevel desc
		";
		// 查询用户信息
		$list = $mysqlTools->selectSql ( $sql );
		if (is_array ( $list )) {
			return $list;
		} else {
			return array ();
		}
	}
	private function findChildLevel($user) {
		global $mysqlTools;
		$sql = "
        	select
				s.roleLevel level
			from
				sys_user u inner join sys_user_role r on u.userId = r.userId
				inner join sys_role s on s.roleId = r.roleId
			where
				u.userIndex like '$user[userIndex]%'
			and u.userState != 4
			group by s.roleLevel
			order by s.roleLevel desc
		";
		// 查询用户信息
		$list = $mysqlTools->selectSql ( $sql );
		if (is_array ( $list )) {
			return $list;
		} else {
			return array ();
		}
	}
	private function isUpgrade($roleList, $item) {
		foreach ( $roleList as $role ) {
			if ($item ["level"] == $role ["level"]) {
				if ($item ["count"] >= $role ["count"]) {
					return true;
				}
			}
		}
		return false;
	}
	private function queryRoleIdByLevel($level) {
		global $mysqlTools;
		$level = $mysqlTools->check_input ( $level );
		$sql = "
		select roleId from sys_role where roleLevel = $level
		";
		// 查询用户信息
		$list = $mysqlTools->selectSql ( $sql );
		if (is_array ( $list ) && ! empty ( $list )) {
			return $list [0] ["roleId"];
		} else {
			return 0;
		}
	}
	private function updateLevel($userId, $level) {
		global $mysqlTools;
		$roleId = $this->queryRoleIdByLevel ( $level );
		$userId = $mysqlTools->check_input ( $userId );
		$roleId = $mysqlTools->check_input ( $roleId );
		$sql = "update `sys_user_role` set `userId` = `userId`" . ",`roleId` = " . $roleId . " where `userId` = " . $userId;
		$result = $mysqlTools->executeSql ( $sql );
		return $result;
	}
	private function upgradeLevel($roleList, $current, $userInfo) {
		$level = 0;
		foreach ( $current as $item ) {
			if ($this->isUpgrade ( $roleList, $item )) {
				if ($item ["level"] + 1 > $userInfo ["roleLevel"] && $item ["level"] + 1 > $level) {
					$this->updateLevel ( $userInfo ["userId"], $item ["level"] + 1 );
				}
				if ($item ["level"] + 1 > $level) {
					$level = $item ["level"] + 1;
				}
			}
		}
	}
	private function getArraysIndex($k, $v, $list) {
		foreach ( $list as $key => $item ) {
			if ($item [$k] == $v) {
				return $key;
			}
		}
		return - 1;
	}
	private function addLevelCount($list) {
		$result = array ();
		foreach ( $list as $item ) {
			foreach ( $item as $row ) {
				$detail = $this->getArraysIndex ( "level", $row ["level"], $result );
				if ($detail != - 1) {
					$result [$detail] ["count"] ++;
				} else {
					$result [] = array (
							"level" => $row ["level"],
							"count" => 1 
					);
				}
			}
		}
		return $result;
	}
	private function upgrade($userId, &$roleList) {
		$userList = $this->getUserListByPid ( $userId );
		$userInfo = $this->getUserRoleInfoById ( $userId );
		$list = array ();
		foreach ( $userList as $user ) {
			$list [] = $this->findChildLevel ( $user );
		}
		$result = $this->addLevelCount ( $list );
		$this->upgradeLevel ( $roleList, $result, $userInfo );
	}
	private function upgradeUser($userId, &$roleList) {
		if (empty ( $userId )) {
			return;
		}
		$this->upgrade ( $userId, $roleList );
		$userInfo = $this->getUserRoleInfoById ( $userId );
		if (! empty ( $userInfo ) && isset ( $userInfo ["userRecom1UserId"] ) && ! empty ( $userInfo ["userRecom1UserId"] )) {
			$this->upgradeUser ( $userInfo ["userRecom1UserId"], $roleList );
		}
	}
	/**
	 * 升级用户后的树型节点升级
	 * 
	 * @param long $userId
	 *        	用户主键Id
	 */
	public function upgradeUserTree($userId) {
		$roleList = $this->queryRole ();
		$userInfo = $this->getUserRoleInfoById ( $userId );
		$this->upgradeUser ( $userInfo ["userRecom1UserId"], $roleList );
	}
}

?>